package com.workspaceapp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.globallogic.myworkspace.R;
import com.globallogic.myworkspace.R.id;
import com.globallogic.myworkspace.R.layout;
import com.globallogic.myworkspace.R.menu;
import com.globallogic.myworkspace.userendpoint.Userendpoint;
import com.globallogic.myworkspace.userendpoint.Userendpoint.InsertRecommend;
import com.globallogic.myworkspace.userendpoint.Userendpoint.ListUserResource;
import com.globallogic.myworkspace.userendpoint.model.MobileData;
import com.globallogic.myworkspace.userendpoint.model.MobileDataCollection;
import com.globallogic.myworkspace.userendpoint.model.Recommend;
import com.globallogic.myworkspace.userendpoint.model.User;
//import com.globallogic.myworkspace.userendpoint.model.UserResource;
//import com.globallogic.myworkspace.userendpoint.model.UserResourceCollection;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.json.jackson.JacksonFactory;
import com.workspaceapp.MainActivity.EndpointsTask;

import android.R.string;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ActionBar.LayoutParams;
import android.app.AlertDialog.Builder;
import android.app.ExpandableListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class ResourceActivity extends Activity {

	final Context context = this;
	ExpandableListView exp;
	String strusername;
	PopupWindow popUp;
	LinearLayout layout;
	TextView tv;
	LayoutParams params;
	EditText txtedit;
	Button bt; 
	
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//popUp = new PopupWindow(this);
	    //layout = new LinearLayout(this);
	   // tv = new TextView(this);
	   // txtedit = new EditText(this);
	   // bt = new Button(this);
		setContentView(R.layout.activity_resource);
		//exp= (ExpandableListView)findViewById(R.id.expandableListView1);
		strusername = getIntent().getExtras().getString("username");
		exp= (ExpandableListView)findViewById(R.id.expandableListView1);
		exp.setOnChildClickListener(new OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				// TODO Auto-generated method stub
				LayoutInflater li = LayoutInflater.from(context);
				View promptsView = li.inflate(R.layout.activity_recommend, null);
				final String resdetails = MyAdapter.childList[groupPosition];
				final String restitle = MyAdapter.parentList[groupPosition];
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
				
				alertDialogBuilder.setView(promptsView);
				
				final EditText userInput = (EditText) promptsView
						.findViewById(R.id.editTextDialogUserInput);
								
				// set dialog message
				alertDialogBuilder
					.setCancelable(false)
					.setPositiveButton("Send",
					  new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog,int id) {
						// get user input and set it to result
						// edit text					    	
					   // RecommendDetails recommend = new RecommendDetails();
					    ArrayList<String> strArr = new ArrayList<String>();
					    
					    strArr.add(userInput.getText().toString());
					    strArr.add(restitle);
					    strArr.add(resdetails);
					    strArr.add(strusername);
						//result.setText(userInput.getText());
					    
					    new RecommendTask().execute(strArr);	
					    
					    }
					  })
					.setNegativeButton("Cancel",
					  new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog,int id) {
						dialog.cancel();
					    }
					  });
 
				// create alert dialog
				AlertDialog alertDialog = alertDialogBuilder.create();
 
				// show it
				alertDialog.show();
				
				
			//	tv.setText("Recommend this to your friend");
			//	popUp.showAtLocation(layout, Gravity.CENTER, 10, 10);					
				//popUp.update(50, 50, 300, 80);
				return false;
			}
		});
    	
    	//params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
       // layout.setOrientation(LinearLayout.VERTICAL);
       // layout.addView(tv, params);
       // layout.addView(txtedit);
       // layout.addView(bt);
       // popUp.setContentView(layout);
        
		new EndpointsTask().execute(strusername);
		
	}
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		// TODO Auto-generated method stub
		super.onWindowFocusChanged(hasFocus);
		exp.setIndicatorBounds(exp.getRight()- 60, exp.getWidth());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.resource, menu);
		return true;
	}
	
	public class EndpointsTask extends AsyncTask<String, Integer, Details> {
		
		protected Details doInBackground(String... strunm) {
			Userendpoint.Builder endpointBuilder = new Userendpoint.Builder(
		              AndroidHttp.newCompatibleTransport(),
		              new JacksonFactory(),
		              new HttpRequestInitializer() {
		              public void initialize(HttpRequest httpRequest) { }
		              });
	      	Userendpoint endpoint = endpointBuilder.build();
	      	Details dt = new Details();
		      try {

		          MobileDataCollection userresource = endpoint.listUserResource(strunm[0]).execute();
		          List<MobileData> userres =  userresource.getItems();
		          
		          List<String> strtit = new ArrayList<String>();
		          List<String> strabs = new ArrayList<String>();
		          
		          
		          for (MobileData ur : userres)
		          {
		        	String strRestitle = ur.get("Title").toString();
		        	String strResAbstrc = ur.get("AbstractRes").toString();
		        	//String strRestitle = strresource.substring(strresource.indexOf("ResourceTitle"), strresource.indexOf("Abstract")-2).replace("ResourceTitle=", "");
		        	//String strResAbstrc = strresource.substring(strresource.indexOf("Abstract"), strresource.indexOf("IsActive")).replace("Abstract={value=", "").replace("},", "");
		        	//  strtit.add(ur.toPrettyString().get("Resource")...toString());
		        	strtit.add(strRestitle);
		        	strabs.add(strResAbstrc);
		        	
		        	dt.title = strtit;
		        	dt.abstrac = strabs;
		        	
		          }
		          //userres.size();
		          return dt;
  	          	          
  	      } catch (IOException e) {
  	        e.printStackTrace();
  	        return dt;
  	      }
          
          
        }
        
        
        @SuppressLint("NewApi")
		protected void onPostExecute(Details result) {
        	
        	String[] arrtit = result.title.toArray(new String[result.title.size()]);
        	String[] arrabs = result.abstrac.toArray(new String[result.abstrac.size()]);
        	exp= (ExpandableListView)findViewById(R.id.expandableListView1);
        	exp.setAdapter(new MyAdapter(getApplicationContext(), arrtit, arrabs));
        	
        }
    }
	
public class RecommendTask extends AsyncTask<ArrayList<String>, Integer, Boolean> {
		
		protected Boolean doInBackground(ArrayList<String>... array) {
			Userendpoint.Builder endpointBuilder = new Userendpoint.Builder(
		              AndroidHttp.newCompatibleTransport(),
		              new JacksonFactory(),
		              new HttpRequestInitializer() {
		              public void initialize(HttpRequest httpRequest) { }
		              });
	      	Userendpoint endpoint = endpointBuilder.build();
	      	
		      try {
		    	  
		    	  
		          Recommend recommend = endpoint.insertRecommend(array[0].get(0),array[0].get(1), array[0].get(2), array[0].get(3)).execute();
		        
		          Boolean status = (Boolean)recommend.get("status");
		        //userres.size();
		          return status;
  	          	          
  	      } catch (IOException e) {
  	        e.printStackTrace();
  	        return false;
  	      }	      
          
          
        }
		

	      protected void onPostExecute(Boolean result) {
	        	
	        	if (result)
	        		Toast.makeText(ResourceActivity.this, "Notification sent successfully!!", Toast.LENGTH_SHORT).show();
	        	else
	        		Toast.makeText(ResourceActivity.this, "Notification failed!!", Toast.LENGTH_SHORT).show();       		
	        }
}

public class Details{

	public List<String> title;
	public List<String> abstrac;
}

public class RecommendDetails{

	public String Email;
	public String ResAbstract;
	public String ResTitle;
	public String UserName;
}
}
